<?php 

function converturl($str) {
    $remove="~ ` ! @ # $ % ^ & * ( ) _ + | \\ = ' \" ; : ? / > . , < ] [ { }";
    $from   = "à á ạ ả ã â ầ ấ ậ ẩ ẫ ă ằ ắ ặ ẳ ẵ è é ẹ ẻ ẽ ê ề ế ệ ể ễ ì í ị ỉ ĩ ò ó ọ ỏ õ ô ồ ố ộ ổ ỗ ơ ờ ớ ợ ở ỡ ù ú ụ ủ ũ ư ừ ứ ự ử ữ ỳ ý ỵ ỷ ỹ đ ";
    $to     = "a a a a a a a a a a a a a a a a a e e e e e e e e e e e i i i i i o o o o o o o o o o o o o o o o o u u u u u u u u u u u y y y y y d ";
    $from  .= " À Á Ạ Ả Ã Â Ầ Ấ Ậ Ẩ Ẫ Ă Ằ Ắ Ặ Ẳ Ẵ È É Ẹ Ẻ Ẽ Ê Ề Ế Ệ Ể Ễ Ì Í Ị Ỉ Ĩ Ò Ó Ọ Ỏ Õ Ô Ồ Ố Ộ Ổ Ỗ Ơ Ờ Ớ Ợ Ở Ỡ Ù Ú Ụ Ủ Ũ Ư Ừ Ứ Ự Ử Ữ Ỳ Ý Ỵ Ỷ Ỹ Đ ";
    $to    .= " a a a a a a a a a a a a a a a a a e e e e e e e e e e e i i i i i o o o o o o o o o o o o o o o o o u u u u u u u u u u u y y y y y d ";
    $remove =  explode(" ", $remove);
    $from =  explode(" ", $from);
    $to =  explode(" ", $to);
    $str = str_replace($from,$to, $str);
    $str = str_replace($remove,"", $str);
    $str=strip_tags($str);
    $str = iconv("UTF-8","ISO-8859-1//TRANSLIT//IGNORE",$str);
    //$str = iconv("ISO-8859-1","UTF-8",$str);
    $str= str_replace(" ","-", $str);
    $str=  strtolower($str);
    
}
session_start();

class product extends CI_Controller  {

        /**
        * Index Page for this controller.
        *
        * Maps to the following URL
        * 		http://example.com/index.php/welcome
        *	- or -  
        * 		http://example.com/index.php/welcome/index
        *	- or -
        * Since this controller is set as the default controller in 
        * config/routes.php, it's displayed at http://example.com/
        *
        * So any other public methods not prefixed with an underscore will
        * map to /index.php/welcome/<method_name>
        * @see http://codeigniter.com/user_guide/general/urls.html
        */
       private $_configs = null;
       function __construct()
        {
            parent::__construct();
            $this->load->helper('url');
            $this->load->library('javascript');
            $this->load->library('session');
            $this->load->library('smarty3','','smarty');
            $this->_configs["title"]="Quản Lý Sản Phẩm";
            $this->_configs["authority"]="product";
            $this->_configs["MinAuthority"]=0;
            $this->load->model('admin-planners/product_model','product_model');
            $this->load->model('admin-planners/region_model','region_model');
            if(!isset($_SESSION["ADP-PRODUCT-DEL"]))$_SESSION["ADP-PRODUCT-DEL"]=true;
            if($this->checkauthority()<0){AccessDenied();}
        }
        
        public function index()
	{
            $this->smarty->assign('_SESSION', $_SESSION);
            $this->smarty->assign('configs', $this->_configs);
            $this->smarty->view('admin-planners/product/01_product','contentofview');
            $this->smarty->view('admin-planners/00_1_styles','styles');
            $this->smarty->view('admin-planners/00_2_scripts','scripts');
            $this->smarty->view('admin-planners/00_3_menus','menus');
            $this->smarty->view('admin-planners/10_template','view');
            $this->smarty->display('admin-planners/01_manage');
	}
        public function checkauthority(){
            if(isset($_SESSION["ADP-USER"]["AUTHORITY"])){
                $myau=-1;
                if(is_array($_SESSION["ADP-USER"]["AUTHORITY"])){
                    foreach ($_SESSION["ADP-USER"]["AUTHORITY"] as $au){
                        if($au["keyword"]=="view" && $myau==-1)$myau=0;
                        if($au["keyword"]=="admin")$myau=1;
                        if($au["keyword"]==$this->_configs["authority"]){
                            if($au["value"]==0 && $myau==-1) $myau=0;
                            if($au["value"]==1) $myau=1;
                        }
                    }
                }
                return $myau>=$this->_configs["MinAuthority"]?$myau:-1;
            }return -1;
        }
        function swicthDel(){
            if(isset($_POST["value"]) && ($_POST["value"]==1 or $_POST["value"]=="1")){
                $_SESSION["ADP-PRODUCT-DEL"]=true;
            }else{
                $_SESSION["ADP-PRODUCT-DEL"]=false;
            }
            $result=array(
                "code"      =>  0,
                "msg"       => "Đã thay đổi tùy chọn hiện dữ liệu xóa."
                );
            
            echo json_encode($result);
        }
        function GenAlbumVal(){
            include APPPATH.'libraries/HTML_DOM/simple_html_dom.php';
            
            $str="<div>".html_entity_decode($_POST["str"])."</div>";
            
            $html = str_get_html($str);
            // Find all images 
            $albums=array();
            $inputs=$html->find("input[type=text]");
            if(is_array($inputs))
            foreach($inputs as $element){ 
                $albums[]=$element->value;
            }
            echo json_encode($albums);
        }
        function GenAlbum(){
            include APPPATH.'libraries/HTML_DOM/simple_html_dom.php';
            
            $str="<div>".$_POST["str"]."</div>";
            $html = str_get_html($str);
            // Find all images 
            $imgs=$html->find('img');
            if(is_array($imgs))
            foreach($imgs as $element){ 
                //if(!startsWith($element->src,"data:"))
                echo '<tr>
                            <td style="position: relative" colspan="2">
                                <div class="_input-label">
                                    <div class="input">
                                        <input type="text" class="auto-album" placeholder="" value="'.$element->src.'">
                                        <div class="label eb"><label>Hình Ảnh</label></div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <input type="button" class="classic-btn" value="Xóa"
                                onclick="delAlbum(this);"
                                />
                            </td>
                        </tr>';
            }
            
        }
        function alias(){
            echo converturl($_POST["str"]);
        }
        public function edit($ProductID=null){
            //$this->smarty->clearCache('admin-planners/new/02_new_edit.tpl');
            if($ProductID!=null){
                $obj=$this->product_model->get($ProductID);
                $obj=objectToArray($obj[0]);
                
                $configs["title"]="Edit";
                
                $configs["obj"]=$obj;
                
    //            $configs["category_list"]=array(
    //                array("id"=>1,"name"=>"Công Nghệ"),
    //                array("id"=>2,"name"=>"Du Lịch"),
    //                array("id"=>4,"name"=>"Gia dụng"),
    //                array("id"=>5,"name"=>"Mỹ Phẩm & Làm Đẹp"),
    //                array("id"=>6,"name"=>"Thời Trang"),
    //                array("id"=>3,"name"=>"Giải Trí")
    //                );
                $albums=  json_decode($configs["obj"]["Album"]);
                $stralbum="";
                if(is_array($albums))foreach ($albums as $a){
                    $stralbum.='
                    <tr>
                        <td style="position: relative" colspan="2">
                            <div class="_input-label">
                                <div class="input">
                                    <input type="text" class="auto-album" placeholder="" value="'.$a.'">
                                    <div class="label eb"><label>Hình Ảnh</label></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <input type="button" class="classic-btn" value="Xóa"
                            onclick="delAlbum(this);"
                            />
                        </td>
                    </tr>';
                }
                $configs["obj"]["stralbums"]="$stralbum";
                $configs["status_list"]=array("Private","Public");
                $configs["status_index"]=$configs["obj"]["Status"]=="Public"?1:0;
            }else{
                $configs["title"]="New";
                $obj=null;
                $configs["obj"]["Categorys"]="";
                $configs["obj"]=$obj;
            }
            $lstregion=  objectToArray($this->region_model->getByParent(0));
            $configs["region_list"]=array();
            foreach ($lstregion as $r){
                $configs["region_list"][]=array(
                    "id"=>$r["id"],
                    "name"=>$r["name"],
                    "checked"=>strpos($configs["obj"]["Regions"], "--".$r["id"]."--")===false?"false":"true");
            }
            

            $this->load->model('admin-planners/category_model','category_model');
            $cates=$this->category_model->gets();
            foreach ($cates as $ca){
                $configs["category_list"][]=array("id"=>$ca->id,"name"=>$ca->name,"checked"=>strpos($configs["obj"]["Categorys"], "--".$ca->id."--")===false?"false":"true");
            }
            
            
            $this->smarty->assign('configs', $configs);
            $this->smarty->display('admin-planners/product/02_product_edit');
        }
        public function editor(){
            $vlows=array("\\\"","\\'");
            $vals=array("\"","'");
            if($this->checkauthority()==1){
                $params=  isset($_POST["params"])?$_POST["params"]:array();
                if(isset($params["Content"])){
                    $params["Content"]=  str_replace($vlows, $vals,$_REQUEST["params"]["Content"]);
                }
                $ProductID=isset($_POST["ProductID"])?$_POST["ProductID"]:"";
                $rok=false;
                
                if($ProductID!=""){
                    $rok=$this->product_model->update($ProductID,$params);
                }else{
                    $rok=$this->product_model->insert($params);
                }
                if($rok){
                    $result=array(
                    "code"      =>  1,
                    "msg"       => "successful."
                    );
                }else{
                    $result=array(
                    "code"      =>  -1,
                    "msg"       => "Error. Can't ".($ProductID!=""?" update.":"insert.")
                    );
                }
            }else{
                $result=array(
                "code"      =>  -1,
                "msg"       => "Please check your authority."
                );
            }
            echo json_encode($result);
        }
        function delete(){
            if($this->checkauthority()==1){
                $ProductID=$_POST["ProductID"];
                $rok=$this->product_model->delete($ProductID);
                if($rok){
                    $result=array(
                    "code"      =>  1,
                    "msg"       => "Sussess."
                    );
                }else{
                    $result=array(
                    "code"      =>  -1,
                    "msg"       => "Error. Can't delete this record."
                    );
                }
            }else{
                $result=array(
                "code"      =>  -1,
                "msg"       => "Cant delete this record.<br/>Please check your authority."
                );
            }
            echo json_encode($result);
            
        }
        function restore(){
            if($this->checkauthority()==1){
                $ProductID=$_POST["ProductID"];
                $rok=$this->product_model->restore($ProductID);
                if($rok){
                    $result=array(
                    "code"      =>  1,
                    "msg"       => "Sussess."
                    );
                }else{
                    $result=array(
                    "code"      =>  -1,
                    "msg"       => "Error. Can't retore this record."
                    );
                }
            }else{
                $result=array(
                "code"      =>  -1,
                "msg"       => "Cant restore this record.<br/>Please check your authority."
                );
            }
            echo json_encode($result);
        }
        
        function g(){
            echo "<pre>";
            print_r($_SESSION);
            echo "</pre>";
        }
        function jqgrid_data(){
            $deals=array();
            $result['total_rows']=0;
            if($this->checkauthority()>=0){
                $result=$this->product_model->gettotal_rows();
                $rows=$result['rows'];
                // get data and store in a json array
                foreach ($rows as $row) {
                    $ca_value="";
                    $ca_arr=  explode("--", "--".$row->CategorysName."--");
                    foreach ($ca_arr as $ca){
                        if($ca!=null && $ca!="")
                        $ca_value.="<span class=\"autho\">$ca</span>";
                    }
                    $re_value="";
                    $re_arr=  explode("--", "--".$row->Regions."--");
                    foreach ($re_arr as $re){
                        if($re!=null && $re!="")
                        $re_value.="<span class=\"autho\">$re</span>";
                    }
                    $deals[] = array(
                        //'id'       => $row->id,
                        '_ProductName_' => "<a target='_blank' href='".  base_url("sanpham/".$row->Alias)."'>".$row->ProductName."</a>",
                        '_Categorys_'   => $ca_value,
                        '_Regions_'     => $re_value,
                        '_StartDate_'   => $row->StartDate,
                        '_EndDate_'     => $row->EndDate,
                        '_UnitPrice_'   => number_format( $row->UnitPrice ),
                        '_Price_'       => number_format( $row->Price ),
                        '_Discontinued_'=> json_encode(array(
                            "_ProductID_"=>$row->ProductID,
                            "_Discontinued_"=>$row->Discontinued
                            
                        )),
                        '_ProductTitle_'=> $row->ProductTitle,
                        '_QuantityPerUnit_'=> $row->QuantityPerUnit,
                        '_Amount_'      => $row->Amount,
                        '_Sold_'        => $row->Sold,
                        '_View_'        => $row->View,
                        '_Status_'      => json_encode(array(
                            "_ProductID_"=>$row->ProductID,
                            "_Status_"=>$row->Status
                            
                        )),
                        '_Supplier_'    => $row->Supplier,
                        '_Label_'       => $row->Label,
                        '_Alias_'       => $row->Alias,
                        '_Insert_'      => $row->Insert,
                        '_Update_'      => $row->Update,
                        '_Product_'   => json_encode(array(
                            "_ProductID_"=>$row->ProductID,
                            "_Delete_"=>$row->Delete,
                            "_Lock_"=>null
                        ))
                    );
                }
            }
            $data[] = array(
                'TotalRows' => $result['total_rows'],
                'Rows' => $deals
            );
            echo json_encode($data);
        }
        
        
        
       
        
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */